package com.ywl.study.sharding.study06.config.range;

import com.ywl.study.sharding.common.config.ExampleConfiguration;
import com.ywl.study.sharding.study03.util.DataSourceUtil;
import org.apache.shardingsphere.api.config.sharding.KeyGeneratorConfiguration;
import org.apache.shardingsphere.api.config.sharding.ShardingRuleConfiguration;
import org.apache.shardingsphere.api.config.sharding.TableRuleConfiguration;
import org.apache.shardingsphere.api.config.sharding.strategy.StandardShardingStrategyConfiguration;
import org.apache.shardingsphere.shardingjdbc.api.ShardingDataSourceFactory;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class ShardingDatabasesAndTablesConfigurationRange implements ExampleConfiguration {
    @Override
    public DataSource getDataSource() throws SQLException {
        ShardingRuleConfiguration shardingConfiguration=new ShardingRuleConfiguration();
        shardingConfiguration.getTableRuleConfigs().add(getOrderTableRuleConfiguration());
        shardingConfiguration.getTableRuleConfigs().add(getOrderItemTableRuleConfiguration());
        shardingConfiguration.getBindingTableGroups().add("t_order,t_order_item");
        shardingConfiguration.getBroadcastTables().add("t_address");
        shardingConfiguration.setDefaultDatabaseShardingStrategyConfig(
                new StandardShardingStrategyConfiguration("user_id",null,null)
        );
        shardingConfiguration.setDefaultTableShardingStrategyConfig(
                new StandardShardingStrategyConfiguration("order_id",null,null)
        );
        return ShardingDataSourceFactory.createDataSource(createDataSourceMap(),shardingConfiguration,new Properties());
    }

    private static Map<String,DataSource> createDataSourceMap(){
        Map<String,DataSource> map=new HashMap<>();
        map.put("demo_ds_0", DataSourceUtil.createDataSource("demo_ds_0"));
        map.put("demo_ds_1",DataSourceUtil.createDataSource("demo_ds_1"));
        return map;
    }

    private static TableRuleConfiguration getOrderTableRuleConfiguration(){
        TableRuleConfiguration result=new TableRuleConfiguration("t_order","demo_ds_${0..1}.t_order_${[0,1]}");
        result.setKeyGeneratorConfig(new KeyGeneratorConfiguration("SNOWFLAKE","order_id",getProperties()));
        return result;
    }

    private static TableRuleConfiguration getOrderItemTableRuleConfiguration(){
        TableRuleConfiguration result=new TableRuleConfiguration("t_order_item","demo_ds_${0..1}.t_order_item_${[0,1]}");
        result.setKeyGeneratorConfig(new KeyGeneratorConfiguration("SNOWFLAKE","order_id",getProperties()));
        return result;
    }

    private static Properties getProperties(){
        Properties result = new Properties();
        result.setProperty("worker.id", "123");
        return result;
    }


}
